<script setup>
  import {
    forecastHours,
    forecast,
    forecastNow
  } from './api.js'
  import futureWeather from './components/FutureWeather/index.vue'
  import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance,
    nextTick
  } from 'vue'
  import {
    onLoad,
    onPageScroll,
    onPullDownRefresh,
  } from '@dcloudio/uni-app'
  const {
    proxy
  } = getCurrentInstance()
  const forecastHoursList = ref([])
  const forecastList = ref([])
  const isScorll = ref(false)
  const swiperHeight = ref(980)
  const searchCity = ref({})
  const today = ref({})
  const currentTemperature = ref('')
  const tempMaxList = ref([])
  const tempMinList = ref([])
  const localArea = ref([])
  const cityDate = ref({})
  const cityLocation = ref([])
  const currentLocation = ref({})
  onLoad((e) => {
    cityLocation.value = uni.getStorageSync('cityCache') || []
    if (e && e.cityList) {
      cityDate.value = JSON.parse(e.cityList)
      forecastNowApi(cityDate.value.adcode)
      forecastHoursApi(cityDate.value.adcode)
      forecastApi(cityDate.value.adcode)
    }
  })

  onPageScroll((e) => {
    if (e.scrollTop > 1) {
      isScorll.value = true
    } else {
      isScorll.value = false
    }
  })
  //实时天气
  const realTime = ref({})
  const forecastNowApi = (async (adcode) => {
    const res = await forecastNow({
      adcode:adcode
    })
    if (res && res.code == 1) {
      realTime.value = res.data
    }
  })
  //24小时天气
  const skycon = ref([])
  const weatherTip = ref('')
  const forecastHoursApi = (async (adcode) => {
    const res = await forecastHours({
      adcode:adcode
    })
    if (res && res.code == 1) {
      if (!res.data.forecast_keypoint) {
        forecastHoursList.value = res.data
        currentTemperature.value = res.data[0].temp
        forecastHoursList.value.forEach(e => {
          e.fxTime = e.fxTime.split('T')[1].split('+')[0]
          e.iconImg = proxy.$getWeatherImage(e.icon)
        })
      } else {
        currentTemperature.value = Math.round(res.data.hourly.temperature[0].value)
        weatherTip.value = res.data.hourly.description.split('，')[0]
        skycon.value = res.data.hourly.skycon
        skycon.value.forEach((e, item) => {
          if (item == 0) {
            e.datetime = "现在"
          } else {
            e.datetime = e.datetime.split('T')[1].split('+')[0]
          }
          e.iconImg = proxy.$getWeatherImage(e.value)
          e.value = proxy.$getWeatherValue(e.value)
        })
      }

    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
  //15天天气
  const AirQuality = ref('')
  const AirQualityValue = ref('')
  const weatherAll = ref({})
  const forecastApi = (async (adcode) => {
    const res = await forecast({
      adcode:adcode
    })
    if (res && res.code == 1) {
      if (!res.data.daily) {
        today.value = res.data[0]
        forecastList.value = res.data
        forecastList.value.forEach((e) => {
          e.weekstate = proxy.$checkDateRelativeToToday(e.fxDate)
          e.textDayImg = proxy.$getWeatherImage(e.iconDay)
          e.textNightImg = proxy.$getWeatherImage(e.iconNight)
          e.week = proxy.$weekdate(e.fxDate)
          e.airQuality = proxy.$getAirQualitySimple(e.aqi)
          let date = new Date(e.fxDate);
          let month = date.getMonth() + 1
          let day = date.getDate();
          e.fxDate = `${month}月${day}日`
        })
        AirQuality.value = proxy.$getAirQuality(res.data[0].aqi)
        AirQualityValue.value = res.data[0].aqi
        tempMaxList.value = res.data.map(e => {
          return +e.tempMax
        })
        tempMinList.value = res.data.map(e => {
          return +e.tempMin
        })
      } else {
        AirQuality.value = proxy.$getAirQuality(res.data.daily.air_quality.aqi[0].max.chn)
        AirQualityValue.value = res.data.daily.air_quality.aqi[0].max.chn
        weatherAll.value = {
          max: Math.round(res.data.daily.temperature[0].max),
          min: Math.round(res.data.daily.temperature[0].min),
          textDay: proxy.$getWeatherValue(res.data.daily.skycon[0].value)
        }
        const temperature = res.data.daily.temperature.map(e => {
          let date = new Date(e.date);
          let month = date.getMonth() + 1
          let day = date.getDate();
          return {
            weekstate: proxy.$checkDateRelativeToToday(e.date),
            week: proxy.$weekdate(e.date),
            fxDate: `${month}月${day}日`
          }
        })
        const skyconmax = res.data.daily.skycon_08h_20h.map(e => {
          return {
            textDay: proxy.$getWeatherValue(e.value),
            textDayImg: proxy.$getWeatherImage(e.value),
          }
        })
        const skyconmin = res.data.daily.skycon_20h_32h.map(e => {
          return {
            textNight: proxy.$getWeatherValue(e.value),
            textNightImg: proxy.$getWeatherImage(e.value),
          }
        })
        const airQuality = res.data.daily.air_quality.aqi.map(e => {
          return {
            airQuality: proxy.$getAirQualitySimple(e.avg.chn)
          }
        })
        const direction = res.data.daily.wind.map(e => {
          return {
            direction: proxy.$judgeWindDirectionByDegree(e.avg.direction),
            speed: proxy.$judgeWindSpeed(e.avg.speed)
          }
        })
        forecastList.value = temperature.map((item, index) => {
          return {
            ...item,
            ...skyconmax[index],
            ...skyconmin[index],
            ...airQuality[index],
            ...direction[index]
          }
        })
        tempMaxList.value = res.data.daily.temperature.map(e => {
          return Math.round(e.max)
        })
        tempMinList.value = res.data.daily.temperature.map(e => {
          return Math.round(e.min)
        })
      }
    }
  })


  function handleTouchStart(e) {
    e.stopPropagation();
  }

  function handleTouchMove(e) {
    e.stopPropagation();
  }

  function onaddCity() {
    const array = {
      ...cityDate.value,
      today: today.value,
      forecastHoursList: forecastHoursList.value,
      currentTemperature: currentTemperature.value,
      forecastList: forecastList.value,
      AirQuality: AirQuality.value,
      AirQualityValue: AirQualityValue.value,
      tempMaxList: tempMaxList.value,
      tempMinList: tempMinList.value
    }
    proxy.$getLocation(array)
    uni.reLaunch({
      url: `/pages/index/index?cityList=${JSON.stringify(cityDate.value)}`
    })
  }
  onPullDownRefresh(async () => {
    await forecastHoursApi(cityDate.value.location_id, cityDate.value.id)
    await forecastApi(cityDate.value.location_id, cityDate.value.id)
    await uni.stopPullDownRefresh();
  })
</script>

<template>
  <view class="home-page" :class="$getWeatherBackground(realTime.icon)">
    <view class="home-bg"
      :style="'background:url('+$getWeatherHomeImage(realTime.icon) +') no-repeat;background-size: contain;'">
    </view>
    <view :class="['home-header', { scrolled: isScorll }]"
      :style="{ backgroundColor: isScorll? $getWeatherHeaderBackground(realTime.icon) :''}">
      <up-navbar :title="`${cityDate.location_name} ${cityDate.adm2_name}`" bgColor="transparent" leftIconSize="48rpx"
        leftIconColor="#fff" safeAreaInsetTop @rightClick="rightClick" :autoBack="true">
      </up-navbar>
    </view>
    <view class="swiper-item uni-bg-red">
      <view class="home-nav">
        <view class="nav-temperature">
          <view class="">{{realTime.temp}}</view>
          <view class="">°</view>
        </view>
        <view class="weather-temperature">
          <view class="weather">{{realTime?realTime.text:weatherAll.textDay}}</view>
          <view class="temperature">
            {{today.tempMax?today.tempMax:weatherAll.max}}°/{{today.tempMin?today.tempMin:weatherAll.min}}°
          </view>
        </view>
        <view class="nav-condition">
          <view class="condition-content" v-if="AirQuality">
            <image src="@/static/icon/leaf.png" mode=""></image>
            <view class="">{{AirQuality}} {{AirQualityValue}}</view>
          </view>
          <view class="condition-content" v-if="weatherTip">
            <image src="@/static/icon/water-line.png" mode=""></image>
            <view class="">{{weatherTip}}</view>
          </view>
        </view>
      </view>
      <view class="forecast-daily">
        <view class="forecast-title">24小时预报{{index}}</view>
        <scroll-view class="forecast-content" scroll-x="true" @touchstart="handleTouchStart"
          @touchmove="handleTouchMove">
          <view class="forecast-nav" :class="index== 0? 'forecast-active':''"
            v-for="item,index in forecastHoursList.length>0?forecastHoursList:skycon" :key="index">
            <view class="forecast-time">{{forecastHoursList.length>0?item.fxTime:item.datetime}}</view>
            <view class="forecast-icon">
              <image :src="item.iconImg" mode=""></image>
            </view>
            <view class="forecast-weather">{{forecastHoursList.length>0?item.text:item.value}}</view>
          </view>
        </scroll-view>
      </view>
      <view class="weather-future">
        <view class="future-title">15天预报</view>
        <futureWeather :listData="forecastList" :tempMaxList="tempMaxList" :tempMinList="tempMinList">
        </futureWeather>
      </view>
    </view>
    <view class="footer">
      <up-button shape="circle" text="添加城市" @click="onaddCity"></up-button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  $fine-color: rgba(141, 173, 252, 1), rgba(48, 94, 209, 1), rgba(19, 61, 168, 1);
  $fine-img: '/static/image/fine.png';

  //晴
  .sunny {
    background: linear-gradient(133.41deg, #8DADFC 0%, #305ED1 63.36%, #133DA8 100%);
  }

  //雨天
  .rainstorm {
    background: linear-gradient(133.41deg, #B5B5B5 0%, #808287 62.8%, #444547 100%);
  }

  //多云
  .cloudy {
    background: linear-gradient(133.41deg, #919CB8 0%, #4E6396 69.3%, #2B3A5E 100%);
  }

  //阴天
  .clear {
    background: linear-gradient(133.41deg, #919CB8 0%, #4E6396 69.3%, #2B3A5E 100%);
  }

  //雾天
  .fog {
    background: linear-gradient(133.41deg, #8DADFC 0%, #305ED1 62.8%, #133DA8 100%);
  }

  //雪天
  .sleet {
    background: linear-gradient(133.41deg, #B5B5B5 0%, #808287 62.8%, #444547 100%);
  }

  //雾霾
  .smog {
    background: linear-gradient(133.41deg, #8F8F8F 0%, #656A75 63.36%, #272D38 100%);
  }

  //沙尘
  .sand-dust {
    background: linear-gradient(133.41deg, #DEB7A0 0%, #6B4A37 63.92%, #423529 100%);
  }

  ::v-deep .u-navbar__content__title {
    color: #fff;
    font-size: 34rpx;
  }

  .uni-bg-red {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-y: scroll;
  }

  .home-bg {
    width: 100%;
    height: 680rpx;
    mix-blend-mode: screen;
    opacity: 1;
    position: absolute;
    top: 0;
    background-size: contain;
    flex-shrink: 0;
  }

  @keyframes navbarAnimation {
    0% {
      opacity: 0;
    }

    100% {
      opacity: 1;
    }
  }

  .scrolled {
    animation: navbarAnimation 0.5s ease-out forwards;
    // background: nth($fine-color, 1);
  }

  .home-header {
    width: 100%;
    height: 88rpx;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding: 0 32rpx;
    flex-shrink: 0;
    position: fixed;
    top: 0;
    transition: background-color 0.3s ease, box-shadow 0.3s ease, transform 0.3s ease;
    z-index: 10;

    .header-content {
      flex: 1;
      text-align: center;
      font-size: 34rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);

    }
  }

  .home-nav {
    width: 100%;
    height: 504rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    .nav-temperature {
      font-size: 144rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      display: flex;

      :last-child {
        font-size: 112rpx;
      }
    }

    .weather-temperature {
      font-size: 34rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      display: flex;
      align-items: center;

      .temperature {
        margin-left: 16rpx;
      }
    }

    .nav-condition {
      display: flex;
      margin-top: 32rpx;

      .condition-content {
        height: 48rpx;
        border-radius: 326rpx;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4rpx 20rpx 4rpx 20rpx;
        box-sizing: border-box;
        margin-left: 24rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);

        image {
          height: 28rpx;
          width: 28rpx;
        }
      }

    }
  }

  .forecast-daily {
    width: 91.5vw;
    height: 280rpx;
    border-radius: 24rpx;
    background: rgba(255, 255, 255, 0.2);
    margin-top: 32rpx;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24rpx 32rpx;
    flex-shrink: 0;

    .forecast-title {
      font-size: 34rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);

    }

    ::v-deep .uni-scroll-view-content {
      display: flex;
      overflow-x: scroll;
    }

    .forecast-content {
      flex: 1;
      overflow-x: auto;
      font-size: 28rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.6);
      margin: 23rpx 0 0 10rpx;
      display: flex;
      align-items: center;
      -webkit-overflow-scrolling: touch;

      :first-child {
        margin-left: 0 !important;
      }

      :last-child {
        margin-right: 0 !important;
      }

      .forecast-active {
        color: rgba(255, 255, 255, 1);
      }

      .forecast-nav {
        display: flex;
        flex-direction: column;
        height: 160rpx;
        align-items: center;
        flex-shrink: 0;
        margin: 0 31rpx;

        .forecast-icon {
          height: 64rpx;
          width: 64rpx;
          margin: 12rpx 0 8rpx;

          image {
            height: 64rpx;
            width: 64rpx;
          }
        }
      }
    }
  }

  .weather-future {
    width: 91.5vw;
    border-radius: 24rpx;
    background: rgba(255, 255, 255, 0.2);
    margin: 32rpx 0 42rpx 0;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24rpx 0 32rpx;

    .future-title {
      font-size: 34rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      padding-left: 32rpx;
    }


  }

  .footer {
    position: fixed;
    bottom: 10rpx;
    width: 50%;
    left: 50%;
    transform: translateX(-50%);

  }
</style>